"""
数据库修复脚本
修复sessions表中缺失的列
"""

import sqlite3
import os

def fix_database():
    """修复数据库中的sessions表"""
    # 数据库文件路径 (假设在项目根目录)
    db_path = os.path.join(os.path.dirname(__file__), 'database.db')
    
    print(f"数据库路径: {db_path}")
    
    # 如果数据库文件不存在，创建它
    if not os.path.exists(db_path):
        print("数据库文件不存在，创建新文件...")
        with open(db_path, 'w') as f:
            pass
    
    try:
        # 连接到数据库
        conn = sqlite3.connect(db_path)
        cursor = conn.cursor()
        
        # 检查sessions表是否存在
        cursor.execute("SELECT name FROM sqlite_master WHERE type='table' AND name='sessions'")
        table_exists = cursor.fetchone()
        
        if not table_exists:
            print("sessions表不存在，创建新表...")
            create_table_sql = """
            CREATE TABLE sessions (
                id VARCHAR(36) PRIMARY KEY,
                name VARCHAR(100) NOT NULL DEFAULT '默认会话',
                user_id VARCHAR(36),
                status VARCHAR(20) NOT NULL DEFAULT 'active',
                category VARCHAR(20) NOT NULL DEFAULT 'default',
                interaction_count INTEGER NOT NULL DEFAULT 0,
                research_count INTEGER NOT NULL DEFAULT 0,
                session_metadata TEXT,
                created_at TIMESTAMP NOT NULL,
                updated_at TIMESTAMP NOT NULL,
                closed_at TIMESTAMP,
                search_vector VARCHAR(1000)
            )
            """
            cursor.execute(create_table_sql)
            print("成功创建sessions表")
        else:
            print("检查sessions表中的列...")
            # 获取现有列
            cursor.execute("PRAGMA table_info(sessions)")
            columns = cursor.fetchall()
            column_names = [column[1] for column in columns]
            
            print(f"现有列: {column_names}")
            
            # 需要确保存在的列
            required_columns = {
                'category': "ALTER TABLE sessions ADD COLUMN category VARCHAR(20) DEFAULT 'default'",
                'search_vector': "ALTER TABLE sessions ADD COLUMN search_vector VARCHAR(1000)"
            }
            
            # 检查并添加缺失的列
            for column_name, alter_sql in required_columns.items():
                if column_name not in column_names:
                    print(f"添加缺失的列: {column_name}")
                    try:
                        cursor.execute(alter_sql)
                        print(f"成功添加列: {column_name}")
                    except Exception as e:
                        print(f"添加列 {column_name} 时出错: {e}")
                else:
                    print(f"列 {column_name} 已存在")
        
        # 提交更改并关闭连接
        conn.commit()
        conn.close()
        print("数据库修复完成!")
        
    except Exception as e:
        print(f"修复数据库时出错: {e}")

if __name__ == "__main__":
    fix_database()